package com.hsxc.cdz.monitor.codec;

import com.hsxc.cdz.monitor.bean.MessageNew;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author 刘力文 对发送的数据进行编码
 */

public class MyEncoder extends MessageToByteEncoder<MessageNew> {

    private Logger logger = LoggerFactory.getLogger(MyEncoder.class);

    @Override
    protected void encode(ChannelHandlerContext ctx, MessageNew msg, ByteBuf out) {
        byte[] result = null;
        try {
            result = msg.getByteFromMessage();
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("ENCODER EXCEPTION");
        }
        out.writeBytes(result);
        logger.info("报文编码为" + byte2hex(result));
        ctx.flush();
        logger.info("SEND MSG TO PILE");
    }

    public static String byte2hex(byte[] buffer) {
        String h = "";
        for (int i = 0; i < buffer.length; i++) {
            String temp = Integer.toHexString(buffer[i] & 0xFF);
            if (temp.length() == 1) {
                temp = "0" + temp;
            }
            h = h + " " + temp;
        }
        return h;
    }
}
